<?php

class FileController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='application.modules.admin.views.layouts.mycolumn';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','admin','delete','download'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new File;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['File']))
		{
			$model->attributes=$_POST['File'];
			$file_path = CUploadedFile::getInstance($model, 'file_path');
			if( is_object($file_path) && get_class($file_path) === 'CUploadedFile' ){
			    $model->file_path = time().rand(1000, 9999).'.'.$file_path->extensionName;
			}else{
			    $model->file_path = 'NoFile.txt';
			}
			$model->file_addtime= time();
			$model->file_size = $file_path->size;
			$model->file_info = $file_path->type;
			if($model->save()){
			    if(is_object($file_path) && get_class($file_path) === 'CUploadedFile'){
			        $file_path->saveAs('./assets/upload/file/'.$model->file_path);
			    }
				$this->redirect(array('view','id'=>$model->file_id));
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$back_file_path =  $model->file_path;
		if(isset($_POST['File']))
		{
			$model->attributes=$_POST['File'];
			$file_path = CUploadedFile::getInstance($model, 'file_path');
			if(!empty($file_path)){
    			if( is_object($file_path) && get_class($file_path) === 'CUploadedFile' ){
    			    $model->file_path = time().rand(1000, 9999).'.'.$file_path->extensionName;
    			}else{
    			    $model->file_path = 'NoFile.txt';
    			}
    			$model->file_addtime= time();
    			$model->file_size = $file_path->size;
    			$model->file_info = $file_path->type;
			}else{
			    $model->file_path=$back_file_path;
			}
			if($model->save()){
			    if(!empty($file_path) && is_object($file_path) && get_class($file_path) === 'CUploadedFile'){
			        $file_path->saveAs('./assets/upload/file/'.$model->file_path);
			    }
			    $this->redirect(array('view','id'=>$model->file_id));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('File');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new File('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['File']))
			$model->attributes=$_GET['File'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	
    public function get_file_size($data,$row){
        $file_size = $data->file_size;
        if( $file_size >= 1024 ) {
            echo intval($file_size/1024)."KB";
        }elseif( $file_size >= 1024*1024 ) {
             echo intval($file_size/(1024*1024))."MB";
        }elseif( $file_size >= 1024*1024*1024 ) {
             echo intval($file_size/( 1024*1024*1024))."GB";
        }else{
            echo intval($file_size)."B";
        }
    }
  

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return File the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=File::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param File $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='file-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionDownload(){
	
	    if (isset($_REQUEST["file_id"])) {
	        $file_id = $_REQUEST["file_id"];
	        $model = File::model()->find('file_id =:file_id', array('file_id' => $file_id));
	        
	        if ($model == null) {
	            throw new CHttpException ('500', '文件不存在');
	        } else {
	            $model->download_times +=1;
	            $model->save();
	            // 服务器端文件的路径
	            $fileName = './assets/upload/file/'.$model->file_path;
	            $pathinfo = pathinfo($fileName);
	            if (file_exists($fileName)){
	                yii::app ()->request->sendFile ($model->file_name.".".$pathinfo['extension'],  file_get_contents ($fileName));
	            }
	        }
	    }
	}
	
}
